<?php
Junction_FileCabinet::using("Junction_Expression_Parser");
Junction_FileCabinet::using("Junction_Expression_Mapping");
Junction_FileCabinet::using("Junction_Core_Mapping");

/**
 * Expression compiler.
 * 
 * <p>The expresison compiler parses Junction expressions and 
 * translates the parsed expressions into valid SQL.
 * 
 * @author Patrick J. Mizer <patrick.mizer@gmail.com>
 * @package junction.expresssion 
 */
class Junction_Expression_Compiler
{
	/**
	 * Raw Junction Expression.
	 * 
	 * @var string
	 */
	private $_expression;
	
	/**
	 * Class mapping.
	 * 
	 * @var Junction_Core_Mapping
	 */
	private $_mapping;
	
	
	/**
	 * Constructor
	 * 
	 * @param Junction_Core_Mapping
	 */
	public function __construct(Junction_Core_Mapping $mapping)
	{
		$this->_mapping = $mapping;
	}
	
	/**
	 * Compile Junction expression into valid SQL WHERE clause.  If no mapping
	 * exists, either in the junction grammar or the class mapping an exception
	 * is thrown.
	 * 
	 * @throws Junction_Expression_Exception
	 * @param string expression
	 * @return string SQL WHERE clause
	 */
	public function compile($expression)
	{
		$parser = new Junction_Expression_Parser();
		$expressionArray = $parser->parse($expression);
		
		$clause = '';
		
		foreach($expressionArray as $token)
		{
			$clause .= $this->_translate($token) . ' ';
		}
		
		return $clause;
	}
	
	/**
	 * Translate token to SQL.
	 * 
	 * @throws Junction_Expression_Exception.
	 * @param string token
	 * @return string translated token 
	 */
	private function _translate($token)
	{
		return Junction_Expression_Mapping::translate($token);
	}
}
?>
